package com.example.customview.bezier.bezier

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View

/**
 * 二阶贝塞尔曲线
 */
class SecondBezierView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null,
    defaultStyle: Int = 0
) : View(context, attributeSet, defaultStyle) {
    private var mLine1Paint: Paint = Paint()

    private var mLine2Paint: Paint = Paint()

    private var mCenterX = 0
    private var mCenterY = 0

    private var mStartPointX = 0
    private var mStartPointY = 0

    private var mEndPointX = 0
    private var mEndPointY = 0
    private var mControlX = 0
    private var mControlY = 0


    init {
        //辅助线
        mLine1Paint.style = Paint.Style.FILL_AND_STROKE
        mLine1Paint.color = Color.BLUE
        mLine1Paint.isAntiAlias = true
        mLine1Paint.textSize = 10f
        mLine1Paint.isFakeBoldText = true



        mLine2Paint.style = Paint.Style.STROKE
        mLine2Paint.color = Color.RED
        mLine2Paint.isAntiAlias = true
        mLine2Paint.textSize = 10f
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        mCenterX = w / 2
        mCenterY = h / 2

        mStartPointX = mCenterX - 300
        mStartPointY = mCenterY

        mEndPointX = mCenterX + 300
        mEndPointY = mCenterY

        mControlX = mCenterX
        mControlY = mCenterY - 200

    }

    override fun onDraw(canvas: Canvas) {

        //先画点
        canvas.drawPoint(mStartPointX.toFloat(), mStartPointY.toFloat(), mLine1Paint)

        canvas.drawPoint(mEndPointX.toFloat(), mEndPointY.toFloat(), mLine1Paint)

        //再画辅助线

        canvas.drawLine(
            mStartPointX.toFloat(),
            mStartPointY.toFloat(), mControlX.toFloat(), mControlY.toFloat(), mLine1Paint
        )
        canvas.drawLine(
            mControlX.toFloat(),
            mControlY.toFloat(), mEndPointX.toFloat(), mEndPointY.toFloat(), mLine1Paint
        )

        //再画贝塞尔曲线

        val path = Path()
        path.moveTo(mStartPointX.toFloat(), mStartPointY.toFloat())
        path.quadTo(
            mControlX.toFloat(), mControlY.toFloat(), mEndPointX.toFloat(),
            mEndPointY.toFloat()
        )
        canvas.drawPath(path, mLine2Paint)

    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {


            }

            MotionEvent.ACTION_MOVE -> {
                mControlX = event.x.toInt()
                mControlY = event.y.toInt()
                invalidate()
            }
        }
        return true
    }
}